<?php

/**
 * Initialize the system
 */
define('TL_MODE', 'FE');
require('system/initialize.php');

class ChangeBackpocket extends Controller
{
	/**
	 * This is class construct function.
	 * @params null
	 * @Return null
	 */
	public function __construct()
	{
		parent::__construct();
		require_once('system/libraries/currency.php');
		$this->obj_currency = new Currency();
	}

	public function changeCart()
	{
		if (!$this->Input->post('FORM_SUBMIT'))
		{
			echo '';exit;
		}
		
		$this->import('Database');
		$this->import('Input');
		
		$arrSessionId = explode('_', $this->Input->post('session_id')); 
		$strCatalogId = $arrSessionId[0];
		$arrCartInfo = array();
		$arrResult = array();
		
		$objColor = $this->Database->prepare("SELECT `id` FROM `catalog_colour` WHERE `title`=?")
									->execute($this->Input->post('color'));
		
		$id_color = $objColor->id;
		
		$objCartInfo = $this->Database->prepare("SELECT `product_catalog`.*,`tl_taxonomy`.`name` as categoryName,`catalog_wrapping`.`title` as gwTitle,`catalog_wrapping`.`img` as gwImg,`catalog_wrapping`.`price` as gwPrice,`tl_catalog_attribute`.`id_catalog`,`tl_catalog_attribute`.`id_color`,`tl_catalog_attribute`.`id_size`,`tl_catalog_attribute`.`catalog_stock`, `tl_catalog_attribute`.`catalog_stock`    
												FROM `product_catalog` 
												LEFT JOIN `tl_taxonomy` ON `product_catalog`.`category`=`tl_taxonomy`.`id` 
												LEFT JOIN `tl_catalog_attribute` ON `tl_catalog_attribute`.`id_catalog`=`product_catalog`.`id`
												LEFT JOIN `catalog_wrapping` ON product_catalog.wrapping=catalog_wrapping.id												
												LEFT JOIN `catalog_colour` ON `catalog_colour`.`id`=`tl_catalog_attribute`.`id_color` 
												WHERE `product_catalog`.`id`=?  
												ORDER BY `tl_catalog_attribute`.`id_color` ASC, `tl_catalog_attribute`.`id_size` ASC")
										->execute($strCatalogId);
		if ($objCartInfo->numRows >= 1)
		{
			$index = 0;
			while ($objCartInfo->next())
			{
				if ($index == 0)
				{
					$arrCartInfo['category'] = $objCartInfo->category;
					$arrCartInfo['name'] = $objCartInfo->name;
					$arrCartInfo['skuid'] = $objCartInfo->skuid;
					$arrCartInfo['price'] = $objCartInfo->price;
					$arrCartInfo['is_wrapping'] = ($objCartInfo->is_wrapping) ? 1 : 0;
					$arrCartInfo['gwPrice'] = $objCartInfo->gwPrice;
				}
				
				//if ($objCartInfo->catalog_stock > 0)
				//{
					if (!isset($arrCartInfo['color'][$objCartInfo->id_color][$objCartInfo->id_size]))
					{
						$arrCartInfo['color'][$objCartInfo->id_color][$objCartInfo->id_size] = array();
					}
					
					$arrCartInfo['color'][$objCartInfo->id_color][$objCartInfo->id_size][] = $objCartInfo->catalog_stock;
				//}
				
				$index++;
			}
		}
		
		$arrResult['session_id'] = $strCatalogId . "_" . ($this->Input->post('size') ? $this->Input->post('size') : $strCatalogSize) . "_" . $this->Input->post('color');
		$imgPath = "daft_files/catalog/products/" . $objCartInfo->skuid  . "/" . $this->Input->post('color') . "/1.jpg";
		$arrResult['td_pic'] = '<a href="./product.html?category=' . $arrCartInfo['category'] . '&amp;id=' . $strCatalogId . '&amp;id_colour=' . $id_color . '&amp;id_size=' . ($this->Input->post('size') ? $this->Input->post('size') : $strCatalogSize) . '"><img alt="' . addslashes($arrCartInfo['name']) . '" src="image.php?src=' . $imgPath . '&amp;width=79&amp;height=79"></a>';
		$arrResult['td_info'] = '<h4><a href="./product.html?category=' . $arrCartInfo['category'] . '&amp;id=' . $strCatalogId . '&amp;id_colour=' . $id_color . '&amp;id_size=' . ($this->Input->post('size') ? $this->Input->post('size') : $strCatalogSize) . '">' . $arrCartInfo['name'] . '</a></h4><small>#'.$arrCartInfo['skuid'].'</small><br/><small>' . $this->obj_currency->change_order(number_format($arrCartInfo['price'], 2, '.', '')) . '</small>' . (($objCartInfo->is_wrapping) ? '<br /><small>GIFT WRAPPING ' . $this->obj_currency->change_order($arrCartInfo['gwPrice']) . '</small>' : '');
		
		if (!isset($arrCartInfo['color']) || !$arrCartInfo['color'])
		{
			$arrResult['td_skin'] = '<p><span class="error">Out of stock - Please remove from your wishlist.</span><a name="remove_backpocket" class="update" title="" href="#" onclick="return fn_remove_backpocket(this);">REMOVE FROM WISHLIST</a></p>';
			
			$arrResult['td_info'] .= '<br /><span class="error">Out of stock - Please remove from your wishlist.</span>';
			$strObjResult = '[{"td_pic" : "' . addslashes($arrResult['td_pic']) . '", "td_skin" : "' . str_replace('\\\n', '', addslashes($arrResult['td_skin'])). '", "td_info" : "' . addslashes($arrResult['td_info']) . '"}]';
			echo $strObjResult;exit;
		}
		elseif (!isset($arrCartInfo['color'][$id_color]) || !$arrCartInfo['color'][$id_color])
		{
			$arrResult['td_skin'] = '<p><label>COLOR</label><select class="color" name="color" onchange="changeColor(this);">'.$this->setColour($this->Input->post('color'), implode(',' , array_keys($arrCartInfo['color']))).'</select></p><p><span class="error">Out of stock - Please remove from your wishlist.</span><a name="remove_backpocket" class="update" title="" href="#" onclick="return fn_remove_backpocket(this);">REMOVE FROM WISHLIST</a></p>';

			$arrResult['td_info'] .= '<br /><span class="error">Out of stock - Please remove from your wishlist.</span>';
			$strObjResult = '[{"td_pic" : "' . addslashes($arrResult['td_pic']) . '", "td_skin" : "' . str_replace('\\\n', '', addslashes($arrResult['td_skin'])). '", "td_info" : "' . addslashes($arrResult['td_info']) . '"}]';
			echo $strObjResult;exit;
		}
		else if($this->Input->post('size') != "" && (!isset($arrCartInfo['color'][$id_color][$this->Input->post('size')]) || !$arrCartInfo['color'][$id_color][$this->Input->post('size')])) 
		{
			$id_size = $this->Input->post('size');
			
			$arrResult['td_skin'] = '<p><label>COLOR</label><select class="color" name="color" onchange="changeColor(this);">'.$this->setColour($this->Input->post('color'), implode(',' , array_keys($arrCartInfo['color']))).'</select></p><p><label>SIZE</label><select class="size" name="size" onchange="changeSize(this);">'.$this->setSize($id_size, implode(',', array_keys($arrCartInfo['color'][$id_color]))).'</select></p><p><span class="error">Out of stock - Please remove from your wishlist.</span><a name="remove_backpocket" class="update" title="" href="#" onclick="return fn_remove_backpocket(this);">REMOVE FROM WISHLIST</a></p>';

			$arrResult['td_info'] .= '<br /><span class="error">Out of stock - Please remove from your wishlist.</span>';
			$strObjResult = '[{"td_pic" : "' . addslashes($arrResult['td_pic']) . '", "td_skin" : "' . str_replace('\\\n', '', addslashes($arrResult['td_skin'])). '", "td_info" : "' . addslashes($arrResult['td_info']) . '"}]';
			echo $strObjResult;exit;
		}
		else
		{
			if ($this->Input->post('size') != "")
				$id_size = $this->Input->post('size');
			else
			{
				$arrId_size = array_keys($arrCartInfo['color'][$id_color]);
				$id_size = $arrId_size[0];
			}
			
			if (!$arrCartInfo['color'][$id_color][$id_size][0]){
				$arrResult['td_skin'] = '<p><label>COLOR</label><select class="color" name="color" onchange="changeColor(this);">'.$this->setColour($this->Input->post('color'), implode(',' , array_keys($arrCartInfo['color']))).'</select><a class="update" name="add_to_cart" title="ADD TO CART" href="#" onclick="return fn_add_to_cart(this);">ADD TO CART</a></p><p><label>SIZE</label><select class="size" name="size" onchange="changeSize(this);">'.$this->setSize($id_size, implode(',', array_keys($arrCartInfo['color'][$id_color]))).'</select><a name="Update_backpocket" class="active" title="UPDATE WISHLIST" href="#" onclick="return fn_update_backpocket(this);"><img src="images/update_wishlist.gif" alt="UPDATE CART" /></a></p><p><span class="error">Out of stock - Please remove from your wishlist.</span><a name="remove_backpocket" class="update" title="" href="#" onclick="return fn_remove_backpocket(this);">REMOVE FROM WISHLIST</a></p>';
				
				$arrResult['td_info'] .= '<br /><span class="error">Out of stock - Please remove from your wishlist.</span>';
				$strObjResult = '[{"td_pic" : "' . addslashes($arrResult['td_pic']) . '", "td_skin" : "' . str_replace('\\\n', '', addslashes($arrResult['td_skin'])). '", "td_info" : "' . addslashes($arrResult['td_info']) . '"}]';
				echo $strObjResult;exit;
			}else{
			
				if ($this->Input->post('quantity') != "")
					$quantity = $this->Input->post('quantity');
				else
					$quantity = 1;
					
				$arrResult['td_skin'] = '<p><label>COLOR</label><select class="color" name="color" onchange="changeColor(this);">'.$this->setColour($this->Input->post('color'), implode(',' , array_keys($arrCartInfo['color']))).'</select><a class="update" name="add_to_cart" title="ADD TO CART" href="#" onclick="return fn_add_to_cart(this);">ADD TO CART</a></p><p><label>SIZE</label><select class="size" name="size" onchange="changeSize(this);">'.$this->setSize($id_size, implode(',', array_keys($arrCartInfo['color'][$id_color]))).'</select><a name="Update_backpocket" class="active" title="UPDATE WISHLIST" href="#" onclick="return fn_update_backpocket(this);"><img src="images/update_wishlist.gif" alt="UPDATE CART" /></a></p><p><label>QUANTITY</label><select class="color" name="quantity" onchange="changeQuantity(this);">'.$this->setQuantity($quantity, $arrCartInfo['color'][$id_color][$id_size][0]).'</select><a name="remove_backpocket" class="update" title="" href="#" onclick="return fn_remove_backpocket(this);">REMOVE FROM WISHLIST</a></p>';

				$strObjResult = '[{"td_pic" : "' . addslashes($arrResult['td_pic']) . '", "td_skin" : "' . str_replace('\\\n', '', addslashes($arrResult['td_skin'])). '", "td_info" : "' . addslashes($arrResult['td_info']) . '"}]';
				echo $strObjResult;exit;
			}
		}
	}
	
	private function setColour($colour,$colour_ids)
	{
		$colourList = $this->getColour();
		$colours = explode(",", $colour_ids);
		
		$strHTML = "";
		for($i=0;$i<count($colours);$i++){
			$key  	  = $colours[$i];
			$selected = ($colour == $colourList[$key]['title']) ? 'selected="selected"' : '';
			$strHTML .= '<option value="'.$colourList[$key]['title'].'" '.$selected.'>'.$colourList[$key]['title'].'</option>\n';
		}
		
		return $strHTML;
	}
	
	private function getSize()
	{
		$dataArray = array();
		$this->import('Database');
		$objRd = $this->Database->execute("SELECT * FROM `catalog_size` Order by id asc");
		
		while ($objRd->next())
		{
			$dataArray[$objRd->id]['size'] = $objRd->size;
		}
		return $dataArray;
	}
	
	private function setSize($size,$size_ids)
	{
		$sizeList	= $this->getSize();
		$sizes		= explode(",", $size_ids);
		
		$strHTML = "";
		for($i=0;$i<count($sizes);$i++){
			$key  	  = $sizes[$i];
			$selected = ($size == $key) ? 'selected="selected"' : '';
			$strHTML .= '<option value="'.$key.'" '.$selected.'>'.$sizeList[$key]['size'].'</option>\n';
		}
		
		return $strHTML;
	}
	
	private function getColour()
	{
		$dataArray = array();
		$objRd = $this->Database->execute("SELECT * FROM `catalog_colour` Order by id asc");
		
		while ($objRd->next())
		{
			$dataArray[$objRd->id]['title'] = $objRd->title;
		}
		return $dataArray;
	}
	
	/**
	 * This function generate the html of quantity
	 * @param int $quantity
	 * @param int $cntStock
	 * @return string html
	 */
	public function setQuantity($quantity, $cntStock=0)
	{
		if (!$quantity || !$cntStock)
			return "";
		
		if ($quantity > $cntStock)
			$quantity = $cntStock;
		
		$strHTML = "";
		for($i=1;$i<=$cntStock;$i++){
			$selected = ($i == $quantity) ? 'selected="selected"' : '';
			$strHTML .= '<option value="'.$i.'" '.$selected.'>'.$i.'</option>\n';
		}
		
		return $strHTML;
	}
}

$action = $_REQUEST['FORM_SUBMIT'];

$cart	= new ChangeBackpocket();

switch($action){
	case "changeCart":
		$cart->changeCart();
		break;	
}
?>